<!--根本不是这个-->
<template>
    <div class="table-panel">
        <!-- <div class="title">
            <p>账号信息</p>
            <el-button class="refresh" type="info" plain icon="el-icon-refresh" @click="refresh">刷新</el-button>
        </div> -->
        <div class="accountSetting-main">
            <!-- <div class="accountSetting-tag">账户设置</div> -->
            <div class="accountSetting-message">
        
                <el-form :model="user" :rules="rules" ref="user" label-width="100px">
                    
                    <el-form-item>
                        <div class="" style="margin-right:10%">
                            <el-row>
                                <el-avatar :src="avatar" shape="square" :size="100" style="margin-left:5px"/>
                            </el-row>
                            <!-- 文件上传按钮 -->
                            <el-row>
                                <el-button style="margin:10px 0" type="success" icon="el-icon-upload" @click="imagecropperShow=true">
                                    {{avatar == null ? '上传' : '更新'}}头像
                                </el-button>
                            </el-row>
                        </div>
                    </el-form-item>
                    <el-form-item label="用户昵称:" prop="nickName">
                        <el-input v-model="user.nickName"></el-input>
                    </el-form-item>
                    <el-form-item label="用户名:" prop="username" required>
                        <el-input v-model="user.username" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="Email:" prop="email">
                        <el-input v-model="user.email"></el-input>
                    </el-form-item>
                    <el-form-item label="旧密码:" prop="oldPwd">
                        <el-input v-model="user.oldPwd" type="password" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="新密码:" prop="newPwd">
                        <el-input v-model="user.newPwd" type="password" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码:" prop="confirmPwd">
                        <el-input v-model="user.confirmPwd" type="password" show-password></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" class="sub-btn" :loading="loading" @click="save">提交</el-button>
                    </el-form-item>
                </el-form>
                <image-cropper
                    v-show="imagecropperShow"
                    :width="300"
                    :height="300"
                    :key="imagecropperKey"
                    :url="BASE_API+'/sys/file/uploadImg'"
                    field="file"
                    @close="close"
                    @crop-upload-success="cropSuccess"/>
            </div>

        </div>
    </div>
</template>

<script>
import accountApi from '@/api/account'
import { mapGetters } from 'vuex'
import md5 from 'js-md5';
import ImageCropper from '@/components/ImageCropper'

const defaultForm = {
  username: '',
  nickName:'',
  password:'',
  newPwd: '',
  oldPwd: '',
  confirmPwd:'',
  salt:'',
  email:''
}
export default {
    components: { ImageCropper },
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                console.log(md5(value) === this.user.password)
                if(md5(value) === this.user.password) {
                     callback(new Error('新旧密码一样，请重新输入密码'));
                } else {
                    if (this.user.confirmPwd !== '') {
                        this.$refs.user.validateField('confirmPwd');
                    }
                }
                callback();
            }
        }
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.user.newPwd) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        }
        var validatePass3 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入旧密码'));
            } else if (md5(value) !== this.user.password) {
                callback(new Error('旧密码输入错误，请重新输入旧密码'));
            } else {
                callback();
            }
        }
        var validateEmail = (rule, value, callback) => {
            const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
            if (!mailReg.test(this.user.email)) {
                return callback(new Error('邮箱格式错误'))
            } else {
                callback()
            }
        }
        return {
            avatar: '',
            user: defaultForm,
            loading:false,
            rules: {
                newPwd: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' }
                ],
                oldPwd: [
                    { required: true, message: '请输入旧密码', trigger: 'blur' },
                    { validator: validatePass3, trigger: 'blur' }
                ],
                confirmPwd: [
                    { required: true, message: '请再次输入密码', trigger: 'blur' },
                    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
                    { validator: validatePass2, trigger: 'blur', required: true }
                ],
                email: [
                    // { required: true, message: '请输入邮箱', trigger: 'blur' },
                    // { validator: validateEmail, trigger: 'blur', required: true }
                ],
                nickName: [
                    { required: true, message: '请输入用户昵称', trigger: 'blur' }
                ]
            },
            //上传弹框组件是否显示
            imagecropperShow:false,
            imagecropperKey:0,//上传组件key值
            BASE_API:process.env.BASE_API, //获取dev.env.js里面地址
        }
    },
    computed: {
        ...mapGetters([
        // 'name',
        // 'avatar'
        ])
    },
    created() {
    // console.log('form created ......')
        // console.log(this.$store.getters.name)
        this.fetchDataByUsername(this.$store.getters.name)
    },
    methods: {
        close() { //关闭上传弹框的方法
            this.imagecropperShow=false
            //上传组件初始化
            this.imagecropperKey = this.imagecropperKey+1
        },
        //上传成功方法
        cropSuccess(data) {
            this.imagecropperShow=false
            //上传之后接口返回图片地址
            this.avatar = data.imgurl
            this.user.salt = data.imgurl
            this.imagecropperKey = this.imagecropperKey+1

            console.log(data.imgurl);

            //更新用户头像
            accountApi.saveUser(this.user).then(response => {
                this.loading = false
                if (response.success) {
                    this.$message({
                        type: 'success',
                        message: response.message
                    })
                }
                this.$store.commit('SET_AVATAR',data.imgurl)
            }).catch(() => {
                this.loading = false
            })
        },
        onSubmit() {
            console.log("submit!")
        },
        refresh() {
            console.log("refresh")
        },
        // 根据id查询记录
        fetchDataByUsername(name) {
            accountApi.getByUsername(name).then(response => {
                // debugger
                // console.log('userinfo')
                // console.log(response.data.userinfo)
                this.user = response.data.userinfo
                this.avatar = response.data.userinfo.salt
                console.log('avatar'+this.avatar);
            })
        },
        save() {
            this.$refs.user.validate(valid => {
                if (valid) {
                    this.loading = true
                    this.user.password = this.user.confirmPwd
                    this.user.salt = this.avatar
                    accountApi.saveUser(this.user).then(response => {
                        this.loading = false
                        if (response.success) {
                            this.$message({
                                type: 'success',
                                message: response.message
                            })
                            
                            console.log("进入退出界面")
                            this.logout()
                            
                        }
                    }).catch(() => {
                        this.loading = false
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '信息输入错误，请重新输入'
                    })
                    return false
                }
            })
        },
        async logout() {
             this.$alert('你已重新修改密码，需要重新登录', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    // this.$message({
                    // type: 'info',
                    // message: `action: ${ action }`
                    // });
                    this.$store.dispatch('LogOut').then(() => {
                    // location.href = '/index';
                    location.reload() // 为了重新实例化vue-router对象 避免bug
                    })
                }
            });
              
        },
    },
}
</script>

<style scoped>
.updateBtn{
    /* margin-bottom: -10px; */
    /* margin-top: 20px; */
    float: right;
}
.accountSetting {
    text-align: center;
    height: 100%;
}

.refresh {
    position: absolute;
    top: 10px;
    right: 10%;
}

.accountSetting .title {
    text-align: left;
    padding-left: 20px;
    border: solid 1px #E4E4E4;
    /* border-left: solid 2px #1ABC9C; */
    height: 35px;
    line-height: 20px;
    background-color: #F3F3F3;
    color: #999999;
    padding-top: 20px;
    /* padding-left: 10%; */
    /* line-height: 40px; */
}

.accountSetting .title p {
    /* height: 20px; */
    margin: 0;
    padding-left: 5px;
    border-left: solid 3px #1ABC9C;
}

.accountSetting-main {
    margin-top: 20px;
    /* border: solid 1px #E4E4E4; */
    /* width: 80%; */
    margin-left: 10%;
    margin-right: 10%;
    /* height: 100%; */
    text-align: center;
    background-color: #ffffff;
}

.accountSetting-tag {
    text-align: left;
    border: solid 1px #E4E4E4;
    height: 50px;
    line-height: 50px;
    background-color: #F3F3F3;
    padding-left: 20px;
    /* margin-left: -1px;
    margin-right: -1px;
    margin-top: -1px; */
    margin: -1px -1px 0px -1px;
    font-size: 13px;
}

.accountSetting-message {
    /* width: 35%; */
    /* margin-left: 30%; */
    margin-top: 50px;
    margin-left: 20%;
    margin-right: 25%;
}

.setting-img {
    margin-left: 22%;
    color: #1ABC9C;
    font-size: 10px;
    margin-top: 20px;
    margin-bottom: 20px;
}

.setting-img img {
    width: 100px;
    height: 100px;
}

.sub-btn {
    text-align: center;
    width: 130px;
}
.el-form-item__label {
        /* width: 100px; */
        font-weight: 0 !important;
        font-size: 13px !important;
        line-height: 32px;
        /* float: left; */
        /* position: absolute; */
    }
</style>